package org.springcloud.wisdom.spring_01_canteen.dishes.cart;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private CartService cartService;
    // 获取购物车中所有商品
    @GetMapping("/getAll")
    public ResponseEntity<List<Cart>> listCarts() {
        List<Cart> carts = cartService.list();
        return ResponseEntity.ok(carts);
    }

    // 添加商品到购物车
    @PostMapping("/add")
    public ResponseEntity<Void> addToCart(@RequestBody Cart cart) {
        cartService.addToCart(cart);
        return ResponseEntity.ok().build();
    }

    // 更新购物车中的商品数量
    @PutMapping("/{id}/quantity")
    public ResponseEntity<Boolean> updateCartQuantity(
            @PathVariable Integer id,
            @RequestParam("newCount") Integer newCount) {
        boolean updated = cartService.updateCartQuantity(id, newCount);
        if (updated) {
            return ResponseEntity.ok(updated);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 从购物车中删除商品
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> removeFromCart(@PathVariable Integer id) {
        cartService.removeFromCart(id);
        return ResponseEntity.ok().build();
    }
    // 清空购物车
    @PostMapping("/clear")
    public ResponseEntity<Void> clearCart() {
        cartService.clearCart(); // 清空 cart 表
        return ResponseEntity.ok().build();
    }
}
